package middleware

import (
	"cat-collage-backend/constant"
	"cat-collage-backend/internal/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"gorm.io/gorm"
	"net/http"
	"strings"
)

const SecretKey = constant.SecretKey

func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "认证不通过，请重新登陆"})
			return
		}

		// 检查是否有 Bearer 前缀
		if !strings.HasPrefix(authHeader, "Bearer ") {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
			return
		}
		// 提取 token 部分
		tokenString := strings.TrimPrefix(authHeader, "Bearer ")

		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("unexpected signing method")
			}
			return []byte(SecretKey), nil
		})

		if err != nil || !token.Valid {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			return
		}
		// 处理 token claims
		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			uid := claims["user_id"].(string)
			user, success := getUserInfo(db, uid)
			if !success || user.Token != tokenString {
				c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "登录已过期，请重新登陆"})
				return
			}
			c.Next()
		} else {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims"})
		}
	}
}

func getUserInfo(db *gorm.DB, userId string) (*model.User, bool) {
	user := &model.User{}
	res := db.Where("id = ?", userId).First(&user)
	if res.Error != nil {
		return nil, false
	}
	return user, true
}
